package com.ecoolex.union.pay.retailer.api.graphql;

import com.ecoolex.framework.modularize.api.auth.user.ConsumerMemberAuthority;
import com.ecoolex.framework.modularize.api.service.device.DeviceInfo;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module.Type;
import com.ecoolex.framework.web.api.graphql2.annotation.QueryField;
import com.ecoolex.union.pay.retailer.core.util.UnionPayUplanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.util.comparator.Comparators;

import java.util.Base64;
import java.util.Iterator;
import java.util.Map;

@GraphQL2Module(type = Type.User,description = "银联国际用户")
public class UplanGraphql {
	
	@Autowired
	private UnionPayUplanService unionPayUplanService;

	@QueryField(field = "generateSign", description = "生成签名")
	public Map<String,String> generateSign(@NonNull Map<String,String> paramters,DeviceInfo deviceInfo, ConsumerMemberAuthority user) {
		String plainText =  build(paramters);
		String resulutSign = Base64.getEncoder().encodeToString(unionPayUplanService.signData(plainText));
		paramters.put("sign",resulutSign);
        return paramters;
	}

	String build(Map<String,String> params){
		Iterator<String> sorted = params.keySet().stream().filter(name ->!"sign".equals(name)).sorted(Comparators.comparable())
				.iterator();
		StringBuilder stringBuilder = new StringBuilder();
		while (sorted.hasNext()){
			String name = sorted.next();
			stringBuilder.append(name).append("=").append(params.get(name));
			if(sorted.hasNext()){
				stringBuilder.append("&");
			}
		}
		return stringBuilder.toString();
	}
}
